<template>
  <n-modal
    v-model:show="showModal"
    :show-icon="false"
    preset="dialog"
    :title="title"
    :style="{ width: props.width + 'px' }"
    @update:show="handleUpdateShow"
  >
    <n-spin :show="modalLoading" content-class="max-h-[80vh] overflow-auto pr-2">
      <n-form :model="formData" :rules="formRules" ref="formRef" label-width="auto" label-placement="top">
        <n-grid :cols="1" :x-gap="24">
          <n-form-item-gi v-if="formData.menuPid != 'ROOT'" label="上级菜单" path="menuPid">
            <n-tree-select
              placeholder="请输入菜单上级"
              v-model:value="formData.menuPid"
              :options="menuOpts"
              key-field="menuId"
              label-field="menuNm"
            />
          </n-form-item-gi>
          <n-form-item-gi label="菜单名称" path="menuNm">
            <n-input placeholder="请输入菜单名称" v-model:value="formData.menuNm" />
          </n-form-item-gi>
          <n-form-item-gi label="图标" path="icon">
            <n-input placeholder="请输入图标" v-model:value="formData.icon" />
          </n-form-item-gi>
          <n-form-item-gi label="路径" path="path">
            <n-input placeholder="请输入路径" v-model:value="formData.path" />
          </n-form-item-gi>
          <n-form-item-gi label="备注" path="rmrk">
            <n-input placeholder="请输入备注" v-model:value="formData.rmrk" type="textarea" :autosize="{ minRows: 3, maxRows: 5 }" />
          </n-form-item-gi>
          <n-form-item-gi label="排序" path="ordrNum">
            <n-input-number placeholder="请输入排序号" v-model:value="formData.ordrNum" />
          </n-form-item-gi>
        </n-grid>
      </n-form>
    </n-spin>
    <template #action>
      <n-space>
        <n-button @click="() => handleUpdateShow(false)">取消</n-button>
        <n-button v-if="hasPermission('bmpch:menu:save', '保存菜单')" type="info" :loading="saveBtnLoading" @click="handleSave">
          <template #icon>
            <n-icon>
              <SaveOutlined />
            </n-icon>
          </template>
          保存
        </n-button>
      </n-space>
    </template>
  </n-modal>
</template>

<script lang="ts" setup>
import { reactive, ref, unref, watch } from 'vue';
import type { FormRules, FormInst } from 'naive-ui';
import { SaveOutlined } from '@vicons/antd';
import { menuQry001, menuGet, menuSav } from '@yanfan/bmpch-tsapi/menu';
import type * as BMPCH from '@yanfan/bmpch-tsapi/types';
import { usePermission } from '@yanfan/common/hooks';

defineOptions({
  name: 'BmpchMenuEdit',
  titl: '菜单编辑',
});

const { hasPermission } = usePermission();

const props = withDefaults(
  defineProps<{
    show: boolean;
    width?: number;
    bizId: string | null;
    menuPid: string | null;
  }>(),
  {
    show: false,
    width: 530,
  },
);

const emits = defineEmits<{
  (e: 'update:show', show: boolean): void;
  (e: 'refresh'): void;
}>();

class FormData {
  menuPid: string | null = '';
  menuId: string | null = '';
  menuNm: string | null = '';
  icon: string | null = '';
  path: string | null = '';
  rmrk: string | null = '';
  ordrNum: number | null = 0;
}

const formRules: FormRules = {};

const title = ref('新建');
const modalLoading = ref(false);
const formRef = ref<FormInst | null>(null);
const showModal = ref(false);
const menuOpts = ref<BMPCH.MenuQry001Output_MenuDto[]>([]);
const saveBtnLoading = ref(false);
const formData = reactive(new FormData());

watch(
  () => unref(props).show,
  (show) => {
    showModal.value = show;
    if (showModal.value) {
      if (props.bizId) {
        title.value = '编辑';
        modalLoading.value = true;
        menuGet({ menuId: props.bizId })
          .then((data) => {
            Object.assign(formData, data);
            loadMenuData();
          })
          .finally(() => {
            modalLoading.value = false;
          });
      } else {
        title.value = '新建';
        Object.assign(formData, new FormData());
        formData.menuPid = props.menuPid;
        loadMenuData();
      }
    } else {
      Object.assign(formData, new FormData());
    }
  },
);

function handleUpdateShow(value: boolean) {
  emits('update:show', value);
}

function handleSave() {
  saveBtnLoading.value = true;
  formRef.value?.validate(async (errors) => {
    if (!errors) {
      menuSav(formData)
        .then((data) => {
          formData.menuId = data.menuId;
          handleUpdateShow(false);
          window.$message.success('保存成功');
          emits('refresh');
        })
        .finally(() => (saveBtnLoading.value = false));
    } else {
      window.$message.error('请填写完整信息');
      saveBtnLoading.value = false;
    }
  });
}

function loadMenuData() {
  menuQry001({}).then((data) => {
    handleLeafNode(data.list);
    menuOpts.value = data.list;
  });
}

function handleLeafNode(nodes: BMPCH.MenuQry001Output_MenuDto[]) {
  nodes.map((node) => {
    if (node.children && node.children.length > 0) {
      handleLeafNode(node.children);
    } else {
      node.isLeaf = true;
    }
  });
}
</script>

<style lang="less" scoped></style>
